package com.ruoyi.bill.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.bill.domain.BillBankPort;
import com.ruoyi.bill.domain.BillPort;
import com.ruoyi.bill.domain.vo.*;
import com.ruoyi.bill.mapper.BillBankPortMapper;
import com.ruoyi.bill.mapper.BillPortMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.bill.domain.bo.BillFinancePortBo;
import com.ruoyi.bill.domain.BillFinancePort;
import com.ruoyi.bill.mapper.BillFinancePortMapper;
import com.ruoyi.bill.service.IBillFinancePortService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 端口财务台账Service业务层处理
 *
 * @author linziheng
 * @date 2024-03-13
 */
@RequiredArgsConstructor
@Service
public class BillFinancePortServiceImpl implements IBillFinancePortService {

    private final BillFinancePortMapper baseMapper;
    private final BillPortMapper billPortMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R matching(){
        //查询当天的两组数据
        List<BillFinancePortVo> billFinancePorts = baseMapper.queryListToday();
        List<BillPortVo> billPorts =  billPortMapper.queryListToday();
        if(billFinancePorts.isEmpty() || billPorts.isEmpty()){
            return R.fail("未查到需要匹配的数据");
        }
        billPorts = billPorts.stream().filter(billPortVo->billPortVo.getAccountTime()!=null).collect(Collectors.toList());

        Map<String, Double> billFinancePortsMap = billFinancePorts.stream().collect(Collectors.groupingBy(BillFinancePortVo::getTemp,Collectors.summingDouble(BillFinancePortVo::getDoubleNum)));
        Map<String, Double> billPortsMap = billPorts.stream().collect(Collectors.groupingBy(BillPortVo::getTemp,Collectors.summingDouble(BillPortVo::getDoubleNum)));
        for (String key : billFinancePortsMap.keySet()) {
            Double value = billPortsMap.get(key);
            if(Objects.equals(value, billFinancePortsMap.get(key))){
                //匹配成功
                baseMapper.update(null,
                    new LambdaUpdateWrapper<BillFinancePort>()
                        .eq(BillFinancePort::getPayer, key.split("~")[0].split("-")[0])
                        .eq(BillFinancePort::getPayee, key.split("~")[0].split("-")[1])
                        .eq(BillFinancePort::getPaymentDate, key.split("~")[1])
                        .set(BillFinancePort::getCheckType, "0"));
                billPortMapper.update(null,
                    new LambdaUpdateWrapper<BillPort>()
                        .eq(BillPort::getRecipient,key.split("~")[0])
                        .eq(BillPort::getAccountTime,key.split("~")[1])
                        .set(BillPort::getAccountType, "0"));
            }
            // 处理key和value
        }
       return R.ok("数据已进行匹配");
    }
    /**
     * 查询端口财务台账
     */
    @Override
    public BillFinancePortVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询端口财务台账列表
     */
    @Override
    public TableDataInfo<BillFinancePortVo> queryPageList(BillFinancePortBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BillFinancePort> lqw = buildQueryWrapper(bo);
        Page<BillFinancePortVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        TableDataInfo<BillFinancePortVo> res = TableDataInfo.build(result);
        res.setFinancePortAmount(baseMapper.sumAmt(bo));
        return res;
    }

    /**
     * 查询端口财务台账列表
     */
    @Override
    public List<BillFinancePortVo> queryList(BillFinancePortBo bo) {
        LambdaQueryWrapper<BillFinancePort> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BillFinancePort> buildQueryWrapper(BillFinancePortBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BillFinancePort> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPaymentDate() != null, BillFinancePort::getPaymentDate, bo.getPaymentDate());
        lqw.eq(bo.getAmount() != null, BillFinancePort::getAmount, bo.getAmount());
        lqw.like(StringUtils.isNotBlank(bo.getPayee()), BillFinancePort::getPayee, bo.getPayee());
        lqw.like(StringUtils.isNotBlank(bo.getPayer()), BillFinancePort::getPayer, bo.getPayer());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckType()), BillFinancePort::getCheckType, bo.getCheckType());
        return lqw;
    }

    /**
     * 新增端口财务台账
     */
    @Override
    public Boolean insertByBo(BillFinancePortBo bo) {
        BillFinancePort add = BeanUtil.toBean(bo, BillFinancePort.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改端口财务台账
     */
    @Override
    public Boolean updateByBo(BillFinancePortBo bo) {
        BillFinancePort update = BeanUtil.toBean(bo, BillFinancePort.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BillFinancePort entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除端口财务台账
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
